package cn.linstudy.http;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author ljp
 * @Date 2021/11/9 11:27
 * @Description Url相关工具类
 */
public class UrlUtils {

    /**
     * 获取请求地址中的某个参数
     *
     * @param url
     * @param name
     * @return
     */
    public static String getParamFromUrl(String url, String name) {
        return urlSplit(url).get(name);
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     *
     * @param url url地址
     * @return url请求参数部分
     */
    private static String truncateUrlPage(String url) {
        String strAllParam = null;
        String[] arrSplit = null;
        url = url.trim();
        arrSplit = url.split("[?]");
        if (url.length() > 1) {
            if (arrSplit.length > 1) {
                for (int i = 1; i < arrSplit.length; i++) {
                    strAllParam = arrSplit[i];
                }
            }
        }
        return strAllParam;
    }

    /**
     * 将参数存入map集合
     *
     * @param url url地址
     * @return url请求参数部分存入map集合
     */
    public static Map<String, String> urlSplit(String url) {
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit = null;
        String strUrlParam = truncateUrlPage(url);
        if (strUrlParam == null) {
            return mapRequest;
        }
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");
            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }

    public static String getParamFromRestfulUrl(String url) {
        String[] split = url.split("/");
        return Arrays.asList(split).get(split.length - 1);
    }

    public static void main(String[] args) {
        System.out
            .println(UrlUtils.getParamFromUrl(
                "https://market.m.taobao.com/app/pm/pmweb/detail/detailV2.html?itemId=656278107104&spm=a2129.23717746.puimod-search-list_4072845440.1&pmid=1_1636420997824&pmtk=20140647.0.0.0.app-home-zc1.waterfalltab_data.2&path=app-home-zc1%2C23717746&track_id=9c08ec9a-87ea-4f16-a8bf-19fad65dcc4c&ttid=36134632667855%40aliauction_android_1.0.4.1&aliapp=pm&sourceType=other&suid=e3996db4-23ba-4a4f-90c0-7861a284310e&ut_sk=1.XU5uXjwvqBUDAJ9cjfF0n7h%2F_32667855_1636420999863.Copy.paimai_app&un=b14bf38604b203209554e02b75a03bae&share_crt_v=1&sp_tk=aVNKOFhFSEFwdWg=&cpp=1&shareurl=true&short_name=h.fTFaWlk&bxsign=scdeDVqNeTcRvqk60jxI-DLbC1fWwyuExZOwdu0axZOTT1PfKDCMwNjD4aiHEuW18D21pGWunrf1rKo8MD3QjD2I9FmH3lJgdEp6aWXpMhr8pdoOZFYCcJ3qlHG0bVQ_3Rg&sm=518f7e&app=chrome",
                "itemId"));
    }
}
